package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.entity.Result;
import com.itheima.pojo.Families;
import com.itheima.service.FamiliesService;

import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 添加体检人
 */
@RequestMapping("/families")
@RestController
public class FamiliesController {
    @Reference
    private FamiliesService familiesService;


    /**
     * @Description 添加体检人信息
     * @Param Families
     * @Return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Families families, HttpSession session) {
        //从cookies中读取所需的member id
        Integer member_id = Integer.parseInt(session.getAttribute("member_id").toString());

        //判断cookie中是否存在,不存在返回false
        //根据families中的身份证信息查询表格中是否已经存在该联系人,已存在就返回false
        Integer famID = familiesService.findByCid(families);
        long count = familiesService.fingFM(member_id, famID);
        if (count >0 ) {
            return new Result(false, "已存在体检人");
        }
        //根据member id和families 对象 添加到关联表
        try {
            familiesService.add(families, member_id);
            return new Result(true, "添加体检人成功");
        } catch (Exception e) {
            return new Result(false, "添加体检人失败");
        }
    }

    /**
     * @Description 查询账号关联的所有体检人信息
     * @Param
     * @Return
     */
    @RequestMapping("/findAll")
    public Result findAll(HttpSession session) {
        //从session中读取所需的member id
        Integer member_id = Integer.parseInt(session.getAttribute("member_id").toString());


        //判断session中是否存在,不存在返回false

        //调用service 根据memberId查询关联的member对象
        try {
            List<Families> datalist = familiesService.findAll(member_id);
            return new Result(true, "体检人信息查询成功", datalist);
        } catch (Exception e) {
            return new Result(false, "体检人信息查询失败");
        }
    }

    /**
     * @Description 根据体检人身份证号删除体检人信息
     * @Param idCard
     * @Return
     */
    @RequestMapping("/deleteByIdCard")
    public Result deleteByIdCard(@RequestBody Families families) {
        long count = familiesService.findOrderByIdCard(families);
        if (count > 0) {
            return new Result(false, "体检人存在预约");
        }

        try {
            familiesService.deleteByIdCard(families);
            return new Result(true, "体检人信息删除成功");
        } catch (Exception e) {
            return new Result(false, "体检人信息删除失败");
        }
    }
}
